<template>
  <div class="form-demo">
    <h3 class="title">新增</h3>
    <van-form ref="formRef" @submit="onSubmit" @reset="onReset">
      <div class="form-content">
        <van-cell-group inset>
          <van-field
            v-model="form.username"
            name="用户名"
            label="用户名"
            placeholder="用户名"
            :rules="[{ required: true, message: '请填写用户名' }]"
            required
            autocomplete="off"
          />
          <van-field
            v-model="form.password"
            type="password"
            name="密码"
            label="密码"
            placeholder="密码"
            :rules="[{ required: true, message: '请填写密码' }]"
            required
            autocomplete="off"
          />
        </van-cell-group>
      </div>

      <div class="action-bar">
        <van-button round block native-type="reset">重 置</van-button>
        <van-button round block type="primary" native-type="submit">提 交</van-button>
      </div>
    </van-form>
  </div>
</template>

<script lang="ts">
export default {
  name: 'crud-add-demo'
}
</script>

<script setup lang="ts">
import type { FormInstance } from 'vant'
import { reactive, ref } from 'vue'
import { Notify } from 'vant'
import { useRouter } from 'vue-router'
import { useStore } from '@/store/index'
import { loadAdd } from '@/api/demo'

const router = useRouter()

const store = useStore()

const loading = ref(false)

const formRef = ref<FormInstance>()

const createForm = () => ({
  username: '',
  password: ''
})

const form = reactive(createForm())

const onSubmit = (values: typeof form) => {
  console.log('onSubmit', values)
  add()
}

const onReset = () => {
  formRef.value?.resetValidation()
  Object.assign(form, createForm())
}

const add = async () => {
  loading.value = true
  try {
    await loadAdd()
    Notify('提交成功')
    router.back()
    store.commit('cacheView/RESET_CACHE_VIEW', 'CrudListDemo')
  } catch (error) {
    console.error('error =>', error)
  } finally {
    loading.value = false
  }
}
</script>
<style lang="scss" scoped>
@import '@/styles/form.scss';
.form-content {
  height: calc(100vh - 58px - 68px - 30px);
  margin: 15px 0;
  overflow-y: auto;
}
</style>
